<?php

namespace App\Http\Controllers\Api;

use App\Models\Employee;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;

class EmployeeController extends BaseController
{
    /**
     * 获取员工列表
     */
    public function index(Request $request)
    {
        try {
            $query = Employee::with(['user', 'department', 'position']);

            // 搜索条件
            if ($request->has('search')) {
                $search = $request->search;
                $query->where(function ($q) use ($search) {
                    $q->where('real_name', 'like', "%{$search}%")
                      ->orWhere('employee_no', 'like', "%{$search}%")
                      ->orWhere('phone', 'like', "%{$search}%")
                      ->orWhereHas('user', function ($q) use ($search) {
                          $q->where('username', 'like', "%{$search}%");
                      });
                });
            }

            // 部门筛选
            if ($request->has('department_id')) {
                $query->where('department_id', $request->department_id);
            }

            // 岗位筛选
            if ($request->has('position_id')) {
                $query->where('position_id', $request->position_id);
            }

            // 状态筛选
            if ($request->has('status')) {
                $query->where('status', $request->status);
            }

            // 入职日期范围
            if ($request->has('hire_date_start')) {
                $query->where('hire_date', '>=', $request->hire_date_start);
            }
            if ($request->has('hire_date_end')) {
                $query->where('hire_date', '<=', $request->hire_date_end);
            }

            // 分页
            $perPage = $request->get('per_page', 15);
            $employees = $query->paginate($perPage);

            return $this->paginate($employees, '获取员工列表成功');
        } catch (\Exception $e) {
            return $this->error('获取员工列表失败：' . $e->getMessage());
        }
    }

    /**
     * 获取员工详情
     */
    public function show(Employee $employee)
    {
        try {
            $employee->load([
                'user',
                'departmentInfo',
                'positionInfo',
                'manager',
                'subordinates',
                'contracts' => function ($query) {
                    $query->latest()->limit(1);
                },
                'educationExperiences',
                'internalExperiences',
                'externalExperiences',
                'familyRelations',
                'abilityAssessments' => function ($query) {
                    $query->latest()->limit(5);
                },
            ]);

            return $this->success($employee, '获取员工详情成功');
        } catch (\Exception $e) {
            return $this->error('获取员工详情失败：' . $e->getMessage());
        }
    }

    /**
     * 创建员工
     */
    public function store(Request $request)
    {
        try {
            DB::beginTransaction();

            $data = $this->validateRequest($request, [
                // 用户信息
                'username' => 'required|string|min:2|max:50|unique:users',
                'phone' => 'required|string|regex:/^1[3-9]\d{9}$/|unique:users',
                'password' => 'required|string|min:6|max:20',

                // 员工基本信息
                'employee_no' => 'required|string|unique:employees',
                'name' => 'required|string|max:100',
                'gender' => 'required|in:male,female',
                'birth_date' => 'required|date|before:today',
                'id_card_number' => 'required|string|regex:/^\d{17}[\dXx]$/|unique:employees',
                'email' => 'nullable|email|unique:employees',
                'address' => 'nullable|string|max:500',
                'emergency_contact' => 'nullable|string|max:100',
                'emergency_phone' => 'nullable|string|regex:/^1[3-9]\d{9}$/',

                // 工作信息
                'hire_date' => 'required|date',
                'contract_start_date' => 'nullable|date',
                'contract_end_date' => 'nullable|date|after:contract_start_date',
                'department_id' => 'required|exists:departments,id',
                'position_id' => 'required|exists:positions,id',
                'basic_salary' => 'required|numeric|min:0',
                'manager_id' => 'nullable|exists:employees,id',
                'work_location' => 'nullable|string|max:200',
                'notes' => 'nullable|string',
            ]);

            // 创建用户账户
            $user = User::create([
                'username' => $data['username'],
                'phone' => $data['phone'],
                'password' => Hash::make($data['password']),
                'status' => 'active',
            ]);

            // 创建员工档案
            $employee = Employee::create([
                'user_id' => $user->id,
                'employee_no' => $data['employee_no'],
                'name' => $data['name'],
                'gender' => $data['gender'],
                'birth_date' => $data['birth_date'],
                'id_card_number' => $data['id_card_number'],
                'phone' => $data['phone'],
                'email' => $data['email'] ?? null,
                'address' => $data['address'] ?? null,
                'emergency_contact' => $data['emergency_contact'] ?? null,
                'emergency_phone' => $data['emergency_phone'] ?? null,
                'hire_date' => $data['hire_date'],
                'contract_start_date' => $data['contract_start_date'] ?? null,
                'contract_end_date' => $data['contract_end_date'] ?? null,
                'department_id' => $data['department_id'],
                'position_id' => $data['position_id'],
                'basic_salary' => $data['basic_salary'],
                'manager_id' => $data['manager_id'] ?? null,
                'work_location' => $data['work_location'] ?? null,
                'status' => 'active',
                'notes' => $data['notes'] ?? null,
            ]);

            DB::commit();

            // 记录操作日志
            $this->logOperation('create', 'employee', [
                'employee_id' => $employee->id,
                'employee_no' => $employee->employee_no,
                'name' => $employee->name,
            ]);

            $employee->load(['user', 'departmentInfo', 'positionInfo', 'manager']);

            return $this->success($employee, '创建员工成功', 201);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error('创建员工失败：' . $e->getMessage());
        }
    }

    /**
     * 更新员工信息
     */
    public function update(Request $request, Employee $employee)
    {
        try {
            DB::beginTransaction();

            $data = $this->validateRequest($request, [
                // 员工基本信息
                'name' => 'sometimes|required|string|max:100',
                'gender' => 'sometimes|required|in:male,female',
                'birth_date' => 'sometimes|required|date|before:today',
                'id_card_number' => ['sometimes', 'required', 'string', 'regex:/^\d{17}[\dXx]$/', Rule::unique('employees')->ignore($employee->id)],
                'email' => ['sometimes', 'nullable', 'email', Rule::unique('employees')->ignore($employee->id)],
                'address' => 'sometimes|nullable|string|max:500',
                'emergency_contact' => 'sometimes|nullable|string|max:100',
                'emergency_phone' => 'sometimes|nullable|string|regex:/^1[3-9]\d{9}$/',
                'phone' => ['sometimes', 'required', 'string', 'regex:/^1[3-9]\d{9}$/', Rule::unique('users')->ignore($employee->user_id)],

                // 工作信息
                'contract_start_date' => 'sometimes|nullable|date',
                'contract_end_date' => 'sometimes|nullable|date|after:contract_start_date',
                'department_id' => 'sometimes|required|exists:departments,id',
                'position_id' => 'sometimes|required|exists:positions,id',
                'basic_salary' => 'sometimes|required|numeric|min:0',
                'manager_id' => 'sometimes|nullable|exists:employees,id',
                'work_location' => 'sometimes|nullable|string|max:200',
                'status' => 'sometimes|required|in:active,probation,regular,suspended,terminated,retired',
                'termination_date' => 'sometimes|nullable|date',
                'termination_reason' => 'sometimes|nullable|string|max:500',
                'notes' => 'sometimes|nullable|string',
            ]);

            // 更新员工信息
            $employee->update($data);

            // 如果更新了手机号，同时更新用户表的手机号
            if (isset($data['phone'])) {
                $employee->user->update(['phone' => $data['phone']]);
            }

            DB::commit();

            // 记录操作日志
            $this->logOperation('update', 'employee', [
                'employee_id' => $employee->id,
                'changes' => $data,
            ]);

            $employee->load(['user', 'departmentInfo', 'positionInfo', 'manager']);

            return $this->success($employee, '更新员工信息成功');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error('更新员工信息失败：' . $e->getMessage());
        }
    }

    /**
     * 删除员工
     */
    public function destroy(Employee $employee)
    {
        try {
            // 检查是否有下属员工
            if ($employee->subordinates()->count() > 0) {
                return $this->error('该员工有下属员工，无法删除');
            }

            // 检查是否有未完成的业务（如合同、考勤等）
            // 这里可以添加更多的业务检查逻辑

            DB::beginTransaction();

            // 删除员工档案
            $employee->delete();

            // 删除用户账户
            $employee->user->delete();

            DB::commit();

            // 记录操作日志
            $this->logOperation('delete', 'employee', [
                'employee_id' => $employee->id,
                'employee_no' => $employee->employee_no,
                'name' => $employee->name,
            ]);

            return $this->success(null, '删除员工成功');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error('删除员工失败：' . $e->getMessage());
        }
    }

    /**
     * 获取员工统计信息
     */
    public function statistics(Request $request)
    {
        try {
            $stats = [
                'total_employees' => Employee::count(),
                'active_employees' => Employee::where('status', 'regular')->count(), // 正式员工
                'probation_employees' => Employee::where('status', 'probation')->count(), // 试用期员工
                'new_hires_this_month' => Employee::whereMonth('hire_date', now()->month)->count(),
                // 'contract_expiring_soon' => Employee::contractExpiring(30)->count(), // 暂时注释，因为缺少合同字段
                'contract_expiring_soon' => 0, // 暂时设为0
                // 'by_department' => Employee::selectRaw('department_id, COUNT(*) as count')->groupBy('department_id')->with('departmentInfo')->get(), // 暂时注释，缺少部门字段
                'by_department' => [], // 暂时设为空数组
                'by_gender' => Employee::selectRaw('gender, COUNT(*) as count')
                    ->groupBy('gender')
                    ->get(),
                'by_status' => Employee::selectRaw('status, COUNT(*) as count')
                    ->groupBy('status')
                    ->get(),
            ];

            return $this->success($stats, '获取员工统计信息成功');
        } catch (\Exception $e) {
            return $this->error('获取员工统计信息失败：' . $e->getMessage());
        }
    }
}
